#!/usr/bin/env python

# Andrew Pennebaker
#
# Based on Colin Edwards' UAC Bypass
# http://www.recursivepenguin.com/index.php?projectID=3

from mechanize import Browser
import sys, re, time, ConfigParser, os, urllib2, signal
from getopt import getopt

def usage():
	print "Usage: %s" % (sys.argv[0])
	print "\n-c|--config <config file>"	
	print "-n|--no-config <options>"
	print "\n-h|--help (usage)"

	sys.exit()

def sig_handler(signum, frame):
	raise IOError, "Timed out"

signal.signal(signal.SIGALRM, sig_handler)

def load(file):
	try:
		config=ConfigParser.ConfigParser()
		config.readfp(open(file))

		d={}

		for key, value in config.items("Defaults"):
			d[key]=value

		return d
	except Exception, e:
		print "Could not open "+file

def login(settings):
	br=Browser()
	br.set_handle_robots(False)
	br.addheaders=[("User-agent", settings["useragent"])];

	try:
		signal.alarm(settings["timeout"])
		br.open(settings["url_wireless"])
		signal.alarm(0)

		br.select_form(name="frmLogin")

		br["username"]=settings["username"]
		br["password"]=settings["password"]
		response=br.submit()
		br.select_form(name="frmGrab")
		response=br.submit()

		return response.read().find(settings["success_wireless"])!=-1
	except:
		br=Browser()
		br.set_handle_robots(False)
		br.addheaders=[("User-agent", settings["useragent"])];

		try:
			signal.alarm(settings["timeout"])
			br.open(settings["url"])
			signal.alarm(0)

			br.select_form(name="frmLogin")

			br["username"]=settings["username"]
			br["password"]=settings["password"]
			response=br.submit()
			br.select_form(name="frmGrab")
			response=br.submit()

			return response.read().find(settings["success"])!=-1
		except:
			return False

def main():
	config=os.getcwd()+"/gilgamesh.ini"
	no_config=False

	systemArgs=sys.argv[1:] # ignore program name

	optlist=[]
	args=[]

	try:
		optlist, args=getopt(systemArgs, "c:nh", ["config", "no-config", "help"])
	except Exception, e:
		usage()

	for option, value in optlist:
		if option=="-h" or option=="--help":
			usage()
		elif option=="-c" or option=="--config":
			config=value
		elif option=="-n" or option=="--no-config":
			no_config=True

	if no_config:
		settings={
			"url": args[0],
			"url_wireless": args[1],
			"useragent": args[2],
			"success": args[3],
			"success_wireless": args[4],
			"timeout": int(args[5]),
			"username": args[6],
			"password": args[7]
		}

		if login(settings):
			sys.exit(0)
		else:
			sys.exit(1)
	else:
		settings=load(config)
		settings["timeout"]=int(settings["timeout"])
		settings["wait"]=int(settings["wait"])

		while True:
			t=time.strftime("%a %d %b %Y %H:%M", time.localtime())

			if login(settings):
				print "Login   "+t
			else:
				print "Failure "+t

			time.sleep(int(settings["wait"]))

if __name__=="__main__":
	try:
		main()
	except KeyboardInterrupt, e:
		pass